<?php


	namespace Admin\Controller;
	use \Think\Controller;

	class BrandController extends Controller{


		public function index(){
			$listrows =5;
			$brandModel = M('Brand');
			$counts = $brandModel->count();
			$page = new \Think\Page($counts,5);
			if(IS_AJAX){
				$page = $page->show();
				echo $page;
			}else{
				$_GET['p'] = $_GET['p'] > ceil($counts/$listrows) ? ceil($counts/$listrows):$_GET['p'];
				$list = $brandModel->page($_GET['p'],$listrows)->select();
				$this -> assign('page',$page->show());
				$this -> assign('list',$list);
				$this -> display();				
			}
			
		}

		public function add(){

			$brandModel = D('Brand');
			$config = [
						'exts' =>['jpg','jpeg','png','gif'],
						'rootPath' => './Public',
						'savePath' => '/Uploads/brand/',
					  ];

		   $fileUpload = new \Think\Upload($config);
		   if(!$brandModel -> create()){
		   		$this -> error($brandModel -> getError(),U('Brand/index'));
		   }else{
		   		if($info = $fileUpload -> upload()){

		   			//上传数据
		   			$brandModel-> logo = $info['logo']['savepath'].$info['logo']['savename'];

		   			if($brandModel-> add()){
		   				$this -> success('添加品牌成功!',U('brand/index'));
		   			}else{
		   				$this -> error('添加品牌失败',U('brand/index'));
		   			}
		   		}else{
		   			$this -> error('添加品牌失败',U('brand/index'));
		   		}
		   }
		}


		public function delete(){
			// dump(M('Brand') -> fetchSql()->delete(I('post.id')));
			$listrows =5;
			$brandModel = M('Brand');
			if($brandModel -> delete(I('post.id'))){
				$list = $brandModel->page(1,$listrows) -> select();
				$this -> assign('list',$list);
				$this -> display('Brand/ajaxIndex');
			}else{
				echo '0';
			}
		}

		public function edit(){

			$config = [
						'exts' =>['jpg','jpeg','png','gif'],
						'rootPath' => './Public',
						'savePath' => '/Uploads/brand/',
					  ];

		   $fileUpload = new \Think\Upload($config);
			$rule   =       [
	  	  						 ['brandname','require','品牌名不能为空'],
	  	  						 ['url','/^((https|http|ftp|rtsp|mms)?:\/\/)+[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/','不是有效的url']
  	  					   ];
			$brandModel = D('Brand');
			if(!$brandModel->validate($rule)->create()){
				$this -> error($brandModel -> getError(),U('Brand/index'));
			}else{

				//没有上传图片
				// $_FILES['logo']['name']
				if(empty($_FILES['logo']['name'])){
					// dump($brandModel -> fetchSql(true)->save());
					if($brandModel -> save()){
						$this -> success('更新成功',U('Brand/index'));
					}else{
						$this -> error('更新失败',U('Brand/index'));
					}
				}else{
   					if($info = $fileUpload -> upload()){

		   			//上传数据
		   			$brandModel-> logo = $info['logo']['savepath'].$info['logo']['savename'];
		   			
			   			if($brandModel-> save()){
			   				$this -> success('修改品牌成功!',U('brand/index'));
			   			}else{
			   				$this -> error('修改品牌失败',U('brand/index'));
			   			}
			   		}else{
			   			$this -> error('修改品牌失败',U('brand/index'));
			   		}
				}
				
			}
		}
	
	}